package logic

import (
	"context"
	"fmt"
	"user-reg8/cache"
	"user-reg8/model"

	"user-reg8/userrpc/internal/svc"
	"user-reg8/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		user = model.User{

			Tel: in.Tel,
		}
		model.DB.Debug().Create(&user)
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("短信验证码错误请重新输入")
	}
	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
